package com.zdjx.util;

import com.zdjx.pojo.ResponseResult;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class HttpConnect {

    public static ResponseResult http(String hostHead, String hostAndPort, String uri, String httpMethon, String params) throws Exception{

        if(hostHead.equals("https")) {
            HTTPSConn.trustEveryone();
        }

        //请求路径
        URL url = new URL(hostHead + "://" + hostAndPort + uri);
        //记录请求前时间
        long startTime = System.currentTimeMillis();

        //拼接请求头
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(httpMethon);
        conn.setRequestProperty("Expect", "100-continue");
        conn.setRequestProperty("X-Unity-Version", "2018.4.23f1");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", "59");
        conn.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 9; PACM00 Build/PPR1.180610.011)");
        conn.setRequestProperty("Host", hostAndPort);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Accept-Encoding", "gzip");

        //传入参数
        byte[] bs = params.getBytes();
        conn.getOutputStream().write(bs);

        //发送
        conn.connect();

        //响应内容
        String responseBody = null;
        if(HttpURLConnection.HTTP_OK == conn.getResponseCode()){
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String readLine = null;
            StringBuffer response = new StringBuffer();
            while(null != (readLine = bufferedReader.readLine())){
                response.append(readLine);
            }
            bufferedReader.close();
            responseBody = response.toString();
        }

        //记录请求结束时间
        long endTime = System.currentTimeMillis();
        //统计请求耗时
        long time = endTime - startTime;

        return new ResponseResult(url.toString(), new Date(), responseBody, time);
    }
}
